#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2010 Bart Bubak (bart.bubak@gmail.com)

# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 
 
import wx
import sys
from lib import *

__version__ = '0.2.2'
__author__ = 'Bartosz Bubak'

class imageFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None,title = "pyCBR")
        iconFile = "images/pyCBR.ico"
        icon = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        self.picturepanel = wx.Panel(self,style = wx.NO_BORDER)
        self.picturepanel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.picturepanel.Bind(wx.EVT_PAINT, self.repaintImage)
        self.SetBackgroundColour('BLACK')
        self.scrollX = 200
        self.scrollY = 200
        self.maxWith = False
        self.maxHeight = False
        self.fullscreen = False
        self.orgImage = None
        self.bmp = None
        self.currentPosition = 0
        self.imagePosition = (5,5)
        self.Show()

    def setFullscreen(self):
        self.fullscreen = not self.fullscreen
        self.maxWith = self.fullscreen
        self.ShowFullScreen(self.fullscreen)

    def changeImagePosition(self, value):
        ''' Changes view \"window\" on the image 
        Used to \"move\" around image
        '''
        self.currentPosition += value
        if self.currentPosition < 0:
          self.currentPosition = 0
        if self.currentPosition > (self.bmp.GetSize()[1] - self.GetSize()[1]):
          self.currentPosition = self.bmp.GetSize()[1] - self.GetSize()[1]

    def OnKeyDown(self, event):
        keycode = event.GetKeyCode()
        #print keycode
        if keycode == wx.WXK_ESCAPE:
            ret  = wx.MessageBox('Are you sure to quit?', 'Question', wx.YES_NO | wx.NO_DEFAULT, self)
            if ret == wx.YES:
                self.Close()
        if keycode == 70:
          self.setFullscreen()
          self.picturepanel.Refresh()
        if keycode == 87:
          self.maxWith = not self.maxWith
          self.picturepanel.Refresh()
        if keycode == wx.WXK_UP:
          self.changeImagePosition(-1 * self.bmp.GetSize()[1]/10)
          self.picturepanel.Refresh()
        if keycode == wx.WXK_DOWN:
          self.changeImagePosition(self.bmp.GetSize()[1]/10)
          self.picturepanel.Refresh()
        if keycode == wx.WXK_PAGEUP:
          self.loadFromBuffer(loader.getPreviousFile())
        if keycode == wx.WXK_PAGEDOWN:
          self.loadFromBuffer(loader.getNextFile())
        if keycode == wx.WXK_SPACE:
          if event.ShiftDown():
            if self.currentPosition >= (self.bmp.GetSize()[1] - self.GetSize()[1]):
              self.changeImagePosition(-1 * int(self.bmp.GetSize()[1]/3) + 1)
            else:
              self.loadFromBuffer(loader.getPreviousFile())
          else:
            if self.currentPosition < (self.bmp.GetSize()[1] - self.GetSize()[1]):
              self.changeImagePosition(int(self.bmp.GetSize()[1]/3)+1)
            else:
              self.loadFromBuffer(loader.getNextFile())
          self.picturepanel.Refresh()
        event.Skip()

    def prepareImage(self, image):
      if image != None:
        if self.maxWith:
          new_width = self.Size.x-10;
          new_height = int((float(self.Size.x) / image.GetSize().x) * image.GetSize().y)
          image.Rescale(new_width, new_height, 1000)
          self.imagePosition = (5,5)
        else:
          posX = (self.picturepanel.Size.x/2) - (image.GetSize().x/2)
          self.imagePosition = (posX,5)
      return image

    def repaintImage(self, event):
        img2 = self.prepareImage(self.orgImage.Copy())
        self.bmp = wx.BitmapFromImage(img2)
        #self.img = wx.StaticBitmap(self.picturepanel,wx.ID_ANY,wx.BitmapFromImage(img2), self.imagePosition)
        dc = wx.PaintDC(self.picturepanel)
        dc.SetBackground(wx.Brush('BLACK'))
        dc.Clear()
        if self.bmp != None:
          dc.DrawBitmap(self.bmp, self.imagePosition[0], self.imagePosition[1] - self.currentPosition)
          if not self.fullscreen:
            self.SetSize(self.bmp.GetSize() + (15,15))
            self.picturepanel.SetFocus()
    
    def loadImage(self, filename):
        self.bmp = wx.Bitmap(filename)
        self.picturepanel.Refresh()
    
    def loadFromBuffer(self, data):
      if data != None:
        self.orgImage = wx.ImageFromStream(data)
        self.currentPosition = 0
        self.picturepanel.Refresh()
        
app = wx.App(redirect = False)
frame = imageFrame()
if len(sys.argv) > 1:
  filename = sys.argv[1]
  loader = fileLoader.imageLoader(filename)
  frame.loadFromBuffer(loader.getCurrentFile())
  print ""
else:
  print "Usage:\npyCBR comicFile.cbz|cbr"
  exit(0)

app.MainLoop()
